import { dialog, BrowserWindow } from 'electron'
import { promises, accessSync } from 'fs'
import path, { basename, parse } from 'path'
import { homedir } from 'os'

export default async function savefile(browserWindow: BrowserWindow, values: string, python: string) {
    let home = path.join(homedir(), 'Desktop')

    try {
        accessSync(home)
    } catch (e) {
        home = path.join(homedir(), '桌面')
    }

    let { filePath } = await dialog.showSaveDialog(browserWindow, {
        title: '保存文件',
        defaultPath: home
    })
    if (filePath) {
        filePath = getfilename(filePath)
        await promises.writeFile(filePath + '.xml', values, 'utf-8')
        await promises.writeFile(filePath + '.py', python, 'utf-8')
    }
}

export function getprojecttilefilename(filename: string): string {
    if (!getprojecttilefilename) return ''
    const matches = basename(filename).match(/^(.*)\.xml?$/)
    if (!matches) {
        return ''
    } else {
        return matches[1].substring(0, 100)
    }
}

function getfilename(filename: string): string {
    const { name, dir } = parse(filename)
    return path.join(dir, name)
}